package demo.dao;

import demo.dao.dto.AlertRule;
import demo.dao.mapper.AlertRuleMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AlertRuleDao {

    private static Logger logger = LoggerFactory.getLogger(AlertRuleDao.class);

    private AlertRuleMapper alertRuleMapper;

    @Autowired
    public void setAlertRuleMapper(AlertRuleMapper alertRuleMapper) {
        this.alertRuleMapper = alertRuleMapper;
    }

    public int insert(AlertRule alertRule) {
        if (alertRule == null) {
            return 0;
        }
        return alertRuleMapper.insertSelective(alertRule);
    }

    public int deleteById(int id) {
        return alertRuleMapper.deleteByPrimaryKey(id);
    }

    public int updateById(int id, AlertRule alertRule) {
        if (alertRule == null) {
            return 0;
        }
        alertRule.setId(id);
        alertRule.setUpdateTime(null);
        return alertRuleMapper.updateByPrimaryKeySelective(alertRule);
    }

    /**
     * 查询所有规则
     *
     * @return
     */
    public List<AlertRule> selectAllActive() {
        Map<String, Object> map = buildQueryParam(null, null, true, null, null);
        return alertRuleMapper.selectByMap(map);
    }

    public int countBy(Map<String, Object> map) {
        return alertRuleMapper.countByMap(map);
    }

    public List<AlertRule> selectBy(Map<String, Object> map) {
        return alertRuleMapper.selectByMap(map);
    }


    /**
     * 构建查询参数
     *
     * @param name
     * @param tag
     * @param nameStr
     * @param remark
     * @return
     */
    public static Map<String, Object> buildQueryParam(
            String name, String tag, Boolean active, String nameStr, String remark) {
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isNotBlank(name)) {
            map.put("name", name);
        }
        if (StringUtils.isNotBlank(tag)) {
            map.put("tag", tag);
        }
        if (active != null) {
            map.put("active", active);
        }
        if (StringUtils.isNotBlank(nameStr)) {
            map.put("nameStr", nameStr);
        }
        if (StringUtils.isNotBlank(remark)) {
            map.put("remark", remark);
        }
        return map;
    }
}
